package com.app.service.impl;

import cn.hutool.core.util.StrUtil;
import com.app.mapper.SysUserMapper;
import com.app.model.SysRole;
import com.app.model.SysUser;
import com.app.service.ISysRoleService;
import com.app.service.ISysUserService;
import com.app.vo.SysUserVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yoominic
 * @since 2023-12-05
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private ISysRoleService iSysRoleService;

    @Override
    public SysUser login(String username, String md5Password) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername, username);
        queryWrapper.eq(SysUser::getPassword, md5Password);
        return sysUserMapper.selectOne(queryWrapper);
    }

    @Override
    public SysUserVo getAdminList(Integer page, Integer limit, String keyword) {
        Page<SysUser> pageRequest = new Page<>(page, limit);
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();

        // 添加关键词搜索条件
        if (StrUtil.isNotBlank(keyword)) {
            queryWrapper.like("username", keyword)
                    .or().like("real_name", keyword);
        }

        // 查询用户分页数据
        Page<SysUser> adminUserPage = sysUserMapper.selectPage(pageRequest, queryWrapper);
        List<SysUser> adminUserList = adminUserPage.getRecords();

        // 批量获取角色名称
        Set<Integer> roleIds = adminUserList.stream()
                .map(SysUser::getRoleId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        Map<Integer, String> roleMap = new HashMap<>();
        if (!roleIds.isEmpty()) {
            List<SysRole> roles = iSysRoleService.listByIds(new ArrayList<>(roleIds));
            roleMap = roles.stream()
                    .collect(Collectors.toMap(SysRole::getId, SysRole::getRoleName));
        }

        // 设置角色名称并清空密码
        for (SysUser adminUser : adminUserList) {
            if (adminUser.getRoleId() != null) {
                adminUser.setRoleName(roleMap.get(adminUser.getRoleId()));
            }
            adminUser.setPassword(null);
        }

        // 构建返回对象
        SysUserVo sysUserVo = new SysUserVo();
        sysUserVo.setList(adminUserList);
        sysUserVo.setCount((int) adminUserPage.getTotal());
        return sysUserVo;
    }

}
